import React, { useState, useEffect, useRef } from 'react';
import { InputNumber, Input, Select, message, Button, Row, Col } from 'antd';
import CustomForm from 'src/components/CustomForm';
import TableEditor from 'src/components/TableEditor';
import { EDGE_TYPE } from 'src/utils/constant';
import Modal from 'src/components/Modal';

import { compare } from 'src/utils/compare';
import { getConditionGroupJson } from 'src/utils/json';
import ExecConditions from '../form/execConditions';
import { cloneDeep } from 'lodash';
import { randomKey } from 'src/utils/utils';

export default function CrossConfig(props) {
  const {
    edge_type,
    projectCode,
    variable,
    edge_configs,
    operator,
    disabled,
    compareData = {},
    using_variables,
    limitType,
  } = props;
  const form = useRef(null);
  const _conditionGroups = useRef(null);
  const [edgeType, setEdgeType] = useState(edge_type || EDGE_TYPE._CONDITION);
  const [edgeConfigs, setEdgeConfigs] = useState(edge_configs || []);

  useEffect(() => {
    edge_type && setEdgeType(edge_type);
  }, [edge_type]);

  useEffect(() => {
    console.log(edge_configs);
    edge_configs && setEdgeConfigs(edge_configs);
  }, [edge_configs]);

  function handleSubmit() {
    form.current.validateFields((err, values) => {
      if (!err) {
        try {
          // 如果是百分比，则需要计算综合是不是等于100
          if (edgeType === EDGE_TYPE._PERCENT) {
            const total = edgeConfigs.reduce((total, it) => {
              total += it.percent || 0;
              return total;
            }, 0);
            if (total !== 100) {
              throw '百分比总和必须等于100%';
            }
          } else if (edgeType === EDGE_TYPE._CONDITION) {
            edgeConfigs.forEach((edge) => {
              getConditionGroupJson(edge.condition_groups);
            });
          }
          props.outEdeges.forEach((it) => {
            const model = it.getModel();
            const currentModel = edgeConfigs.find(
              (item) => item.source === model.source && item.target === model.target,
            );
            const edge = {
              label: currentModel.name,
              source: currentModel.source,
              target: currentModel.target,
              id: currentModel.id,
            };
            // 如果是百分比，则把线上也加上百分比，方便展示在线上
            if (edgeType === EDGE_TYPE._PERCENT && currentModel.percent) {
              edge.percent = currentModel.percent;
            } else {
              edge.percent = null;
            }
            //更新线
            props.onUpdateEdge && props.onUpdateEdge(it, edge);
          });
          // 更新node
          props.onUpdateNode &&
            props.onUpdateNode({
              edge_type: edgeType,
              edge_configs: edgeConfigs.map((edge) => {
                const base = { name: edge.name, source: edge.source, target: edge.target, id: edge.id };
                if (edgeType === EDGE_TYPE._PERCENT) {
                  return { ...base, percent: edge.percent };
                } else if (edgeType === EDGE_TYPE._CONDITION) {
                  return { ...base, condition_groups: edge.condition_groups };
                } else {
                  return base;
                }
              }),
            });
        } catch (error) {
          message.warning(error);
        } finally {
          console.log('hehe');
        }
      }
    });
  }

  // 打开条件配置
  function openConditionsConfig(record, index) {
    console.log(record, compareData);
    const key = randomKey();
    const _compareData =
      (compareData &&
        compareData.edge_configs &&
        compareData.edge_configs[index] &&
        compareData.edge_configs[index].condition_groups) ||
      [];
    const _index = Modal.open({
      title: '配置分流条件',
      width: '1000px',
      content: (
        <div style={{ padding: '0 20px' }}>
          <ExecConditions
            isOld={props.isOld}
            isCompare={props.isCompare}
            value={record.condition_groups || []}
            variable={variable}
            using_variables={using_variables}
            operator={operator}
            createRef={_conditionGroups}
            disabled={disabled}
            compareData={_compareData}
            projectCode={projectCode}
            limitType={limitType}
            modelId={key}
          />
        </div>
      ),
      maskClosable: false,
      isOkBtn: disabled ? false : true,
      isCancelBtn: disabled ? false : true,
      key: key,
      ok: () => {
        _conditionGroups.current.getValue((value, error) => {
          if (!error) {
            handleChange(record, value);
            Modal.close(_index);
          }
        });
      },
      cancel: () => {
        Modal.close(_index);
      },
    });
  }

  const formItems = [
    {
      label: {
        label: '分流模式',
        className: 'tantuer-form-item3 tantuer-form-item-nowrap',
      },
      name: 'edge_type',
      options: {
        initialValue: edgeType,
        rules: [{ required: true, message: '请选择条件' }],
      },
      component: (
        <Select
          style={{ width: '200px', ...compare({ ...props, value: { edge_type: edgeType } }, 'edge_type') }}
          disabled={props.disabled}
          onChange={(value) => setEdgeType(value)}
        >
          {[{ key: EDGE_TYPE._PERCENT, value: '百分比' }, { key: EDGE_TYPE._CONDITION, value: '条件' }].map((it) => {
            return (
              <Select.Option value={it.key} key={it.key}>
                {it.value}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
  ].filter(Boolean);

  const columnsTestIn = [
    {
      dataIndex: 'index',
      key: 'index',
      width: 60,
      render: (text, record, index) => {
        return <span style={{ paddingLeft: '12px' }}>{index + 1}</span>;
      },
    },
    {
      title: '流向名称',
      dataIndex: 'name',
      key: 'name',
      width: '60%',
      render: (text, record, index) => {
        return (
          <Input
            defaultValue={text}
            onChange={(e) => handleChangeNameInput(e.target.value, record, index)}
            disabled={props.disabled}
            style={{
              width: '150px',
              ...compare({ ...props, value: edge_configs, compareData: compareData.edge_configs }, index, 'name'),
            }}
          />
        );
      },
    },
    edgeType === EDGE_TYPE._CONDITION
      ? {
          title: '操作',
          dataIndex: 'condition',
          key: 'condition',
          render: (text, record, index) => {
            const compares = {
              ...props,
              value: {
                stringify:
                  JSON.stringify(edge_configs && edge_configs[index] && edge_configs[index].condition_groups) || [],
              },
              compareData: {
                stringify: JSON.stringify(
                  (compareData &&
                    compareData.edge_configs &&
                    compareData.edge_configs[index] &&
                    compareData.edge_configs[index].condition_groups) ||
                    [],
                ),
              },
            };
            return (
              <Button
                type='link'
                onClick={() => openConditionsConfig(record, index)}
                className={disabled ? 'ant-btn-link-dark' : null}
                style={compare(compares, 'stringify')}
              >
                {disabled ? '查看' : '配置'}
              </Button>
            );
          },
        }
      : {
          title: '百分比',
          dataIndex: 'percent',
          key: 'percent',
          render: (text, record, index) => {
            return (
              <Row type='flex' gutter={10} align='middle'>
                <Col>
                  <InputNumber
                    min={0}
                    max={100}
                    value={text || 0}
                    formatter={(value) => `${value}%`}
                    onChange={(value) => handleChangePercentInput(value, record)}
                    disabled={props.disabled}
                    style={{
                      ...compare(
                        { ...props, value: edge_configs, compareData: compareData.edge_configs },
                        index,
                        'percent',
                      ),
                    }}
                  />
                </Col>
                <Col>(流量1%~99%)</Col>
              </Row>
            );
          },
        },
  ];

  function handleChangePercentInput(value, record) {
    record.percent = value;
    setEdgeConfigs(cloneDeep(edgeConfigs));
  }

  function handleChangeNameInput(value, record, index) {
    edgeConfigs[index] = { ...record, name: value };
    setEdgeConfigs(cloneDeep(edgeConfigs));
  }

  function changeHandlePercentInput(datas) {
    setEdgeConfigs(cloneDeep(datas));
  }

  function handleChange(record, value) {
    record.condition_groups = value;
    setEdgeConfigs(cloneDeep(edgeConfigs));
  }
  return (
    <div>
      <CustomForm
        colNum={1}
        createForm={(ref) => (form.current = ref)}
        formItems={formItems}
        onHandleSubmit={() => handleSubmit()}
        className='warning-setting'
        hideSubmit={props.disabled}
        confirmText='提交'
      >
        <div style={{ padding: '0 24px 24px 30px' }}>
          <TableEditor
            columns={columnsTestIn}
            initItem={{ name: '', percent: 0 }}
            dataSource={edgeConfigs}
            onChange={changeHandlePercentInput}
            noNeedAdd={true}
            getButtonGroup={() => []}
          />
        </div>
      </CustomForm>
    </div>
  );
}
